<template>
  <a-spin :spinning="confirmLoading">
    <a-row v-for="(model,index) in models" :key="index" style="width:800px">
      <a-col :span="7">
        <a-form-item label="模型名称:" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-checkbox :checked="model.check" @change="checkModel($event,model)">
            {{ model.name }}
          </a-checkbox>
        </a-form-item>
      </a-col>
      <tree-temp-select :ref="model.id" :model="model" @change="changeTemplate"></tree-temp-select>
    </a-row>
  </a-spin>
  </a-modal>
</template>

<script>
  import {
    listModel
  } from '@/api/site/model'
  import { saveModelBatch } from '@/api/site/category'
  import treeTempSelect from './treeTempSelect.vue'
  export default {
    components: {
      treeTempSelect
    },
    data () {
      return {
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 7
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 13
          }
        },
        confirmLoading: false,
        reloading: false,
        categoryId: null,
        models: [],
        treeData: []
      }
    },
    created () {

    },
    methods: {
      listModel () {
        listModel({ categoryId: this.categoryId }).then(response => {
          if (response.code === 0) {
             this.models = response.res
          }
        })
      },
      setCategoryId (categoryId) {
         this.categoryId = categoryId
         this.listModel()
      },
      changeTemplate (id, value, label, extra) {
        if (this.models.length > 0) {
          for (let i = 0; i < this.models.length; i++) {
            const model = this.models[i]
            if (model.id === id) {
                model.templatePath = extra.triggerNode.dataRef.relativePath
            }
          }
        }
      },
      checkModel (e, model) {
         model.check = e.target.checked
      },
      handleSubmit () {
          const models = this.getCheckModelData()
          if (models.length > 0) {
              saveModelBatch(models).then(response => {
                if (response.code === 0) {
                  this.$emit('ok')
                  this.$message.info('保存成功!')
                } else {
                  this.$message.error(response.msg)
                }
              })
          } else {
            this.$message.error('模型不能为空')
          }
      },
      getCheckModelData () {
        const models = []
        if (this.models.length > 0) {
          for (let i = 0; i < this.models.length; i++) {
            const model = this.models[i]
            if (model.check) {
                models.push({
                   modelId: model.id,
                   categoryId: this.categoryId,
                   templatePath: model.templatePath
                })
            }
          }
        }
        return models
      },
      handleCancel () {

      }
    }
  }
</script>
